package com.xiaotao.util;

import com.alibaba.fastjson.JSON;
import com.xiaotao.entity.CardVerify;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class CardVerifyUtil {

    public static CardVerify cardVerify(String frontImg, String backImg) {
        String host = "https://cardnumber.market.alicloudapi.com/rest/160601/ocr/ocr_idcard.json?spm=5176.product-detail.debug.1.332d4c85rok1XO&file=ocr_idcard.json";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String method = "POST";
        String appcode = "a8316032089743b1bb0108892e8cea58";

        // -------------------------- 2. 正面识别（独立请求头，解决403）--------------------------
        // 正面专属请求头：每次请求生成新的X-Ca-Nonce
        Map<String, String> frontHeaders = new HashMap<>();
        frontHeaders.put("Authorization", "APPCODE " + appcode);
        frontHeaders.put("Content-Type", "application/json; charset=UTF-8");
        frontHeaders.put("X-Ca-Nonce", UUID.randomUUID().toString()); // 正面唯一随机串
        Map<String, String> querys = new HashMap<>();

        CardVerify frontCard = null; // 提前声明，避免作用域报错
        try {
            // 构建正面请求体
            String frontJson = buildJsonBody(frontImg, "face");
            // 发送正面请求
            HttpResponse frontResp = HttpUtils.doPost(host, path, method, frontHeaders, querys, frontJson);

            // 处理正面响应：判空+UTF-8编码，避免乱码和空指针
            if (frontResp != null) {
                int frontStatusCode = frontResp.getStatusLine().getStatusCode();
                System.out.println("正面响应状态码：" + frontStatusCode);

                if (frontStatusCode == 200) {
                    // 强制UTF-8编码，防止中文乱码导致解析失败
                    String frontResult = EntityUtils.toString(frontResp.getEntity(), "UTF-8");
                    System.out.println("正面识别结果：" + frontResult);

                    // 解析正面结果：判空后再转，避免JSON格式错误
                    if (frontResult != null && !frontResult.isEmpty()) {
                        frontCard = JSON.parseObject(frontResult, CardVerify.class);
                    }
                }
            }

            // 正面解析失败处理：避免后续调用frontCard.getSuccess()空指针
            if (frontCard == null) {
                frontCard = new CardVerify();
                frontCard.setSuccess(false);
                frontCard.setConfig_str("正面识别失败或响应格式异常");
                return frontCard;
            }

        } catch (Exception e) {
            // 正面异常处理：兜底，避免崩溃
            e.printStackTrace();
            frontCard = new CardVerify();
            frontCard.setSuccess(false);
            frontCard.setConfig_str("正面识别异常：" + e.getMessage());
            return frontCard;
        }

        // -------------------------- 3. 反面识别（独立请求头，解决403；无报错）--------------------------
        CardVerify backCard = new CardVerify(); // 提前初始化，避免空指针
        try {
            // 反面专属请求头：新的X-Ca-Nonce，不复用正面的
            Map<String, String> backHeaders = new HashMap<>();
            backHeaders.put("Authorization", "APPCODE " + appcode);
            backHeaders.put("Content-Type", "application/json; charset=UTF-8");
            backHeaders.put("X-Ca-Nonce", UUID.randomUUID().toString()); // 反面唯一随机串

            // 构建反面请求体
            String backJson = buildJsonBody(backImg, "back");
            System.out.println("反面请求体：" + backJson);

            // 发送反面请求
            HttpResponse backResp = HttpUtils.doPost(host, path, method, backHeaders, querys, backJson);

            // 处理反面响应
            if (backResp != null) {
                int backStatusCode = backResp.getStatusLine().getStatusCode();
                System.out.println("反面响应状态码：" + backStatusCode);

                if (backStatusCode == 200) {
                    // 强制UTF-8编码，避免乱码
                    String backResult = EntityUtils.toString(backResp.getEntity(), "UTF-8");
                    System.out.println("反面原始响应：" + backResult);

                    // 解析反面结果：判空后再转
                    if (backResult != null && !backResult.isEmpty()) {
                        backCard = JSON.parseObject(backResult, CardVerify.class);
                    } else {
                        backCard.setSuccess(false);
                        backCard.setConfig_str("反面响应为空，无法解析");
                    }
                } else {
                    backCard.setSuccess(false);
                    backCard.setConfig_str("反面请求失败，状态码：" + backStatusCode);
                }
            } else {
                backCard.setSuccess(false);
                backCard.setConfig_str("反面未获取到响应");
            }

        } catch (Exception e) {
            // 反面异常处理：兜底
            e.printStackTrace();
            backCard.setSuccess(false);
            backCard.setConfig_str("反面识别异常：" + e.getMessage());
        }

        // -------------------------- 4. 合并结果（无空指针报错）--------------------------
        if (frontCard.getSuccess() && backCard.getSuccess()) {
            // 合并反面信息到正面
            frontCard.setStart_date(backCard.getStart_date());
            frontCard.setEnd_date(backCard.getEnd_date());
            frontCard.setIssue(backCard.getIssue());
            return frontCard;
        } else {
            // 识别失败：返回详细原因，避免信息不全
            CardVerify error = new CardVerify();
            error.setSuccess(false);
            error.setConfig_str("识别失败：正面=" + frontCard.getSuccess() + "，反面=" + backCard.getSuccess()
                    + "，原因：" + frontCard.getConfig_str() + "；" + backCard.getConfig_str());
            return error;
        }
    }

    /**
     * 构建JSON请求体（无报错）
     */
    private static String buildJsonBody(String base64, String side) {
        // 用普通HashMap构建，避免匿名内部类可能的编译报错
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("image", base64); // 前端传递的纯Base64（无前缀）

        Map<String, Object> configMap = new HashMap<>();
        configMap.put("side", side); // "face"=正面，"back"=反面
        configMap.put("quality_info", false); // 不返回质量分

        requestMap.put("configure", configMap);
        return JSON.toJSONString(requestMap);
    }
}